﻿using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel;
using DeklaritModel;
using MVCApplication.Helpers;

namespace MVCApplication.Controllers
{
    public class CiudadController : CommonController
    {
		#region Properties
		
		protected DeklaritModel.CiudadDataSet  dsCiudadDataSet1;
		
		[Browsable(false)]
        public virtual ICiudadDataAdapter DataAdapter 
        {
            get 
            {
                return DataAdapterFactory.GetCiudadDataAdapter(); 
            }
        }
		
		#endregion
		
		#region WorkWith Action
		
        public ActionResult WorkWith(bool? prompt, string returnItems, string fillByMethod, string filterValues)
        {
            dsCiudadDataSet1 = new CiudadDataSet();
            int totalRecords, currentPage;
            FillDataSet(fillByMethod, filterValues, (int?)Session["m_WorkWithCiudadCurrentPage"], out totalRecords, out currentPage);
            UpdateWorkWithPagerViewData(totalRecords, currentPage);
            ViewData["Prompt"] = prompt;
            ViewData["ReturnItems"] = returnItems != null ? returnItems.Split(',') : null;
            if (!(prompt ?? false))
            {
				SaveState();
            }
            return View(dsCiudadDataSet1);
        }

        private void FillDataSet(string FillByMethod, string FilterValues, int? defaultCurrentPage, out int totalRecords, out int currentPage)
        {
            totalRecords = -1;
            currentPage = -1;

            if (!string.IsNullOrEmpty(FillByMethod))
            {
				
                switch (FillByMethod)
                {
					case "FillByPaisId" :
                        string[] splitted = GeneralFunctions.GetSplittedText(FilterValues);
                        if (splitted != null && FilterValues.Length >= 1)
                        {
                            totalRecords = DataAdapter.GetRecordCountByPaisId(System.Int16.Parse(splitted[0]));
                            currentPage = GetCurrentPage(totalRecords, defaultCurrentPage ?? 1);
                            DataAdapter.FillPageByPaisId(dsCiudadDataSet1, System.Int16.Parse(splitted[0]), (currentPage - 1) * GridPageSize, GridPageSize);
                        }
						break;
                    default:
                        break;
                }
            }
            if (currentPage == -1)
            {
                totalRecords = DataAdapter.GetRecordCount();
                currentPage = GetCurrentPage(totalRecords, defaultCurrentPage ?? 1);
                DataAdapter.FillPage(dsCiudadDataSet1, (currentPage - 1) * GridPageSize, GridPageSize);
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult WorkWith(bool? prompt, string returnItems, int currentPage, int totalRecords, bool? expandRecords, int? rowIndex, string fillByMethod, string filterValues)
        {
			if(expandRecords.HasValue && expandRecords.Value)
			{
				GetDataSet();
                CiudadDataSet expandedDS = new CiudadDataSet();
                DataAdapter.Fill(expandedDS, dsCiudadDataSet1.Ciudad[rowIndex.Value].PaisId, dsCiudadDataSet1.Ciudad[rowIndex.Value].CiudadId);
                ViewData["CiudadExpandedModel"] = expandedDS;
                ViewData["ExpandedRowIndex"] = rowIndex;
                ViewData["ExpandRecords"] = true;				
			}
			else
			{
				Session["m_WorkWithCiudadCurrentPage"] = currentPage;
				dsCiudadDataSet1 = new CiudadDataSet();
                FillDataSet(fillByMethod, filterValues, currentPage, out totalRecords, out currentPage);
            }
            UpdateWorkWithPagerViewData(totalRecords, currentPage);
            ViewData["Prompt"] = prompt;
            ViewData["ReturnItems"] = returnItems != null ? returnItems.Split(',') : null;
            if(!(prompt ?? false))
            {
				SaveState();
            }
			return this.PartialView("WorkWithControl", dsCiudadDataSet1);
        } 
        
        #endregion

		#region Create Action

        public ActionResult Create(bool? prompt, string promptReturnFunction, string promptAttribute, string instantiatedAttributes)
        {
			dsCiudadDataSet1 = new CiudadDataSet();
			GeneralFunctions.ChangeTablesDefaults(dsCiudadDataSet1.Ciudad);
			CiudadDataSet.CiudadRow row = dsCiudadDataSet1.Ciudad.NewCiudadRow();
            InstantiateAttributes(row, instantiatedAttributes);
			dsCiudadDataSet1.Ciudad.AddCiudadRow(row);
			SaveState();
            ViewData["Mode"] = EnumMode.Insert;
            ViewData["Prompt"] = prompt;
            ViewData["PromptReturnFunction"] = promptReturnFunction;
            ViewData["PromptAttribute"] = promptAttribute;
			return View("Edit", dsCiudadDataSet1);
        }
        
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(bool? prompt, string promptReturnFunction, string promptAttribute, string instantiatedAttributes, Int16? PaisId, Int16? CiudadId, string CiudadNombre, MenuAction menuAction)
        {
			GetDataSet();
            // Validation logic
            ValidateCiudad(PaisId, CiudadId, CiudadNombre, EnumMode.Insert, true);
            if (!ModelState.IsValid)
            {
                ViewData["Mode"] = EnumMode.Insert;
				SetReadOnlyToInstantiateAttributes(instantiatedAttributes);
                if (prompt ?? false)
                {
					ViewData["Prompt"] = prompt;
					ViewData["PromptAttribute"] = promptAttribute;
					return this.PartialView("EditControl", dsCiudadDataSet1);
                }
                else
                {
					return View("Edit", dsCiudadDataSet1);
                }
            }

            // Database logic
            try
            {                
                CiudadDataSet.CiudadRow row = dsCiudadDataSet1.Ciudad.Rows[0] as CiudadDataSet.CiudadRow;
				if (PaisId.HasValue)
					row.PaisId = PaisId.Value;
				else
					row.PaisId = 0;
				if (CiudadId.HasValue)
					row.CiudadId = CiudadId.Value;
				else
					row.CiudadId = 0;
				row.CiudadNombre = CiudadNombre;
                DataAdapter.Update(dsCiudadDataSet1);
                switch (menuAction)
                {
                    case MenuAction.Submit:
                        string dummy = UrlHistory.Pop(Session);
                        return RedirectToAction("Edit", new { PaisId = row.PaisId, CiudadId = row.CiudadId });
                    case MenuAction.SubmitAndNew:
                        return RedirectToAction("Create");
                    case MenuAction.SubmitAndReturn:
                        if (prompt ?? false)
                        {
                            ViewData["Prompt"] = true;
                            ViewData["PromptAttribute"] = promptAttribute;
                            ViewData["PromptReturn"] = true;
                            ViewData["Mode"] = EnumMode.Insert;
                            return this.PartialView("EditControl", dsCiudadDataSet1);
                        }
                        else
                        {
                            return RedirectToAction("Return");
                        }
                    default:
                        throw new System.Exception("Invalid MenuAction: " + menuAction.ToString());
                }
            }
            catch(System.Exception exc)
            {
                ModelState.AddModelError("generalError", exc.Message);
				SetReadOnlyToInstantiateAttributes(instantiatedAttributes);
                ViewData["Mode"] = EnumMode.Insert;
                if (prompt ?? false)
                {
					ViewData["Prompt"] = prompt;
					ViewData["PromptAttribute"] = promptAttribute;
					return this.PartialView("EditControl", dsCiudadDataSet1);
                }
                else
                {
					return this.PartialView("Edit", dsCiudadDataSet1);
                }
            }
        }
		
		#endregion
		
		#region Edit Action

        public ActionResult Edit(Int16 PaisId, Int16 CiudadId)
        {
            ViewData["Mode"] = EnumMode.Update;
            try
            {
				dsCiudadDataSet1 = new CiudadDataSet();
				DataAdapter.Fill(dsCiudadDataSet1, PaisId, CiudadId);
				SaveState();
				return this.PartialView("Edit", dsCiudadDataSet1);
            }
            catch (System.Exception exc)
            {
                ModelState.AddModelError("generalError", exc.Message);
                return this.PartialView("Edit");
            }
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(string CiudadNombre, MenuAction menuAction)
        {
			GetDataSet();
            ValidateCiudad(null, null, CiudadNombre, EnumMode.Update, false);
            if (!ModelState.IsValid)
            {
				ViewData["Mode"] = EnumMode.Update;
                switch (menuAction)
                {
                    case MenuAction.Submit:
                        return this.PartialView("EditControl", dsCiudadDataSet1);
                    case MenuAction.SubmitAndReturn:
						return View("Edit", dsCiudadDataSet1);
                    default:
                        throw new System.Exception("Invalid MenuAction: " + menuAction.ToString());
                }
            }

            try
            {				
                CiudadDataSet.CiudadRow row = dsCiudadDataSet1.Ciudad[0];
				row.CiudadNombre = CiudadNombre;
                DataAdapter.Update(dsCiudadDataSet1);
                switch (menuAction)
                {
                    case MenuAction.Submit:
						ViewData["Mode"] = EnumMode.Update;
                        ModelState.AddModelError("generalMsg", "Data succesfully saved.");
                        return this.PartialView("EditControl", dsCiudadDataSet1);
                    case MenuAction.SubmitAndReturn:
                        return RedirectToAction("Return");
                    default:
                        throw new System.Exception("Invalid MenuAction: " + menuAction.ToString());
                }
            }
            catch(System.Exception exc)
            {
                ModelState.AddModelError("generalError", exc.Message);
				ViewData["Mode"] = EnumMode.Update;
                switch (menuAction)
                {
                    case MenuAction.Submit:
                        return this.PartialView("EditControl", dsCiudadDataSet1);
                    case MenuAction.SubmitAndReturn:
						return View("Edit", dsCiudadDataSet1);
                    default:
                        throw new System.Exception("Invalid MenuAction: " + menuAction.ToString());
                }
            }
        }

		#endregion
		
		#region Display Action

        public ActionResult Display(Int16 PaisId, Int16 CiudadId)
        {
            ViewData["Mode"] = EnumMode.Display;
            try
            {
				dsCiudadDataSet1 = new CiudadDataSet();
				DataAdapter.Fill(dsCiudadDataSet1, PaisId, CiudadId);
				SaveState();
				return this.PartialView("Edit", dsCiudadDataSet1);
            }
            catch (System.Exception exc)
            {
                ModelState.AddModelError("generalError", exc.Message);
                return this.PartialView("Edit");
            }
        }		
		#endregion
		
		#region Delete Action

		[AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Delete(Int16 PaisId, Int16 CiudadId)
        {
            ViewData["Mode"] = EnumMode.Delete;
            try
            {
				dsCiudadDataSet1 = new CiudadDataSet();
				DataAdapter.Fill(dsCiudadDataSet1, PaisId, CiudadId);
				SaveState();
				return this.PartialView("Edit", dsCiudadDataSet1);
            }
            catch (System.Exception exc)
            {
                ModelState.AddModelError("generalError", exc.Message);
                return this.PartialView("Edit");
            }
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Delete()
        {
			GetDataSet();
            try
            {
                CiudadDataSet.CiudadRow row = dsCiudadDataSet1.Ciudad[0];
                row.Delete();
                DataAdapter.Update(dsCiudadDataSet1);
                return RedirectToAction("Return");
            }
            catch (System.Exception exc)
            {
                ModelState.AddModelError("generalError", exc.Message);
                dsCiudadDataSet1.RejectChanges();
                ViewData["Mode"] = EnumMode.Delete;
                return this.PartialView("Edit", dsCiudadDataSet1);
            }
        }
		
		#endregion
		
		#region NewRelated and DisplayRelated Actions

		#endregion
		
		#region Auxiliar Methods
        
        private void GetDataSet() 
        {
            //  Get DataSet from Page Session 
			dsCiudadDataSet1 = ((CiudadDataSet)(Session["DataSetCiudad"]));
		}
        
        private void SaveState() 
        {
            //  Save DataSet in Page Session 
			Session.Add("DataSetCiudad", dsCiudadDataSet1 );
		}
		
        protected void ValidateCiudad(Int16? PaisId, Int16? CiudadId, string CiudadNombre, EnumMode mode, bool validateKey)
        {
			if(validateKey)
			{
			if (!(PaisId.HasValue && PaisId.Value != 0))
                ModelState.AddModelError("PaisId", "Id Pais is required.");
			if (!(CiudadId.HasValue && CiudadId.Value != 0))
                ModelState.AddModelError("CiudadId", "Id is required.");
			}
            /*if (contactToValidate.FirstName.Trim().Length == 0)
                ModelState.AddModelError("FirstName", "First name is required.");
            if (contactToValidate.LastName.Trim().Length == 0)
                ModelState.AddModelError("LastName", "Last name is required.");
            if (contactToValidate.Phone.Length > 0 && !Regex.IsMatch(contactToValidate.Phone, @"((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}"))
                ModelState.AddModelError("Phone", "Invalid phone number.");
            if (contactToValidate.Email.Length > 0 && !Regex.IsMatch(contactToValidate.Email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"))
                ModelState.AddModelError("Email", "Invalid email address.");*/
        }

        protected void UpdateWorkWithPagerViewData(int totalRecords, int currentPage)
        {
            ViewData["CurrentPage"] = currentPage;
            ViewData["TotalRecords"] = totalRecords;
            int totalPages = (int)System.Math.Ceiling((double)totalRecords / GridPageSize);
            if (totalPages <= 1)
            {
                ViewData["isFirstPage"] = true;
                ViewData["isLastPage"] = true;
            }
            else
            {
                ViewData["isFirstPage"] = (currentPage <= 1);
                ViewData["isLastPage"] = (currentPage >= totalPages);

                ViewData["lastPage"] = totalPages;
            }
            ViewData["PagerText"] = string.Format(Deklarit.Resources.Resources.pagerRows, totalRecords <= 0 ? 0 : (currentPage - 1) * GridPageSize + 1, Math.Min(currentPage * GridPageSize, totalRecords), totalRecords) + " - " + string.Format(Deklarit.Resources.Resources.pagerPage, currentPage, totalPages <= 0 ? 1 : totalPages);
        }
		
		#endregion
    }
}
